//
//  SettingViewController.m
//  Honda
//
//  Created by Xiaolong Zhang on 13-7-3.
//  Copyright (c) 2013年 HeninHoo. All rights reserved.
//

#import "SettingViewController.h"
#import "NetworkDefine.h"
#import "NetworkManager.h"
#import "CarInfo.h"
#import "ZipArchiveManager.h"

@interface SettingViewController ()

@end

@implementation SettingViewController
@synthesize carsArr     =   _carsArr;
@synthesize settingView =   _settingView;

static SettingViewController* s_instance = nil;
+ (SettingViewController*)shareInstance {
    if (nil == s_instance) {
        s_instance = [[SettingViewController alloc] init];
    }
    
    return s_instance;
}

- (id)init {
    self = [super init];
    if (self) {
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(carInfoShouldUpdate:) name:NotificationCarInfoShouldUpdate object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addCarInfo:) name:NotificationReloadDownloadSourceByAddCarName object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteCarInfo:) name:NotificationReloadDownloadSourceByDeleteCarName object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showingAlertViewForDownloadCars) name:NotificationDidCheckSourceFile object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onStartDownload:) name:NotificationStartDownloadCarTask object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onCancelDownload:) name:NotificationCancelDownloadCarTask object:nil];
    }
    
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    SafeRelease(_settingView);
    SafeRelease(_carsArr);
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.settingView layoutSettingView];
    self.settingView.carsArr = self.carsArr;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (NSMutableArray*)carsArr {
    if (nil == _carsArr) {
        _carsArr = [[NSMutableArray alloc] init];
//        {//车种资源
//            NSDictionary* dic = [[ConfigCodeHelper shareInstance].sourceDic objectForKey:@"cars"];
//            
//            NSArray* carsKeys = dic.allKeys;
//            NSArray* sortedKeys = [carsKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//                return [obj1 compare:obj2 options:NSNumericSearch];
//            }];
//            
//            for (NSString* key in sortedKeys) {
//                CarInfo* car = [[CarInfo alloc] init];
//                car.name = key;
//                
//                [_carsArr addObject:car];
//                SafeRelease(car);
//            }
//        }
        
        {//走进广本资源
            CarInfo* companyInfo = [[CarInfo alloc] init];
            companyInfo.name = @"company.zip";
            [_carsArr addObject:companyInfo];
            SafeRelease(companyInfo);
        }
        
        {//video
            NSDictionary* videoDic = [[ConfigCodeHelper shareInstance].sourceDic objectForKey:@"video"];
            
            NSArray* videoKeys = videoDic.allKeys;
            NSArray* sortedKeys = [videoKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                return [obj1 compare:obj2 options:NSNumericSearch];
            }];
            
            for (NSString* key in sortedKeys) {
                
//                if([key isEqualToString:@"com_T8.mp4"])
//                {
                CarInfo* carVideo = [[CarInfo alloc] init];
                carVideo.name = key;
                [_carsArr addObject:carVideo];
                    SafeRelease(carVideo);

//                }
                

            }
        }
    }
    
    return _carsArr;
}

- (SettingView*)settingView {
    if (nil == _settingView) {
        _settingView = [[SettingView alloc] init];
        _settingView.delegate = self;
        [self.view addSubview:_settingView];
    }
    
    return _settingView;
}

#pragma mark -
- (void)carInfoShouldUpdate:(NSNotification*)notify {
    NSString* name = notify.object;
    
    for (CarInfo* car in self.carsArr) {
        if ([car.name isEqualToString:name]) {
            if (![name hasSuffix:@".zip"])
            {
                car.urlStr = [NSString stringWithFormat:@"%@video/%@", PadDataURL, name];
            } else {
                car.urlStr = [NSString stringWithFormat:@"%@%@", PadDataURL, name];
            }
        


            car.downloadCarObj = [[NetworkManager getInstance] GetDownLoadObjectWithName:name URL:car.urlStr];
            
            if (Downloading_State == car.downloadCarObj.state && [car.downloadCarObj isKindOfClass:[DownloadCarObj class]]) {
                [self onStartDownloadTaskAsyncByCarInfo:car];
            }
            
            break;
        }
    }
    
    self.settingView.carsArr = self.carsArr;
}

- (void)addCarInfo:(NSNotification*)notify {
    NSString* carName = notify.object;

    for (CarInfo* car in self.carsArr) {
        if ([car.name isEqualToString:carName]) {
            return;
        }
    }
    
   CarInfo* carInfoa = [[CarInfo alloc] init];
//   if([carName isEqualToString:@"com_T8.mp4"]||[carName isEqualToString:@"company.zip"])
//    {
    carInfoa.name = carName;
   
    [self.carsArr addObject:carInfoa];
    
    self.settingView.carsArr = self.carsArr;
//    }
}

- (void)deleteCarInfo:(NSNotification*)notify {
    NSString* carName = notify.object;
    
    for (CarInfo* car in self.carsArr) {
        if ([car.name isEqualToString:carName]) {
            [self.carsArr removeObject:car];
            break;
        }
    }
    
    self.settingView.carsArr = self.carsArr;
}

- (void)showingAlertViewForDownloadCars {
    NSString* title = nil;
    for (CarInfo* car in self.carsArr) {
        if ((Default_State == car.downloadCarObj.state || DownloadError_State == car.downloadCarObj.state) && [NSString validString:car.urlStr]) {

            if ([NSString invalidString:title]) {
                
//                if([car.name isEqualToString:@"company.zip"]||[car.name isEqualToString:@"com_T8.mp4"])
//                {
                title = NSLocalizedStringFromTable(car.name, @"InfoPlist", nil);
//                }

            }
            else
            {
//                if([car.name isEqualToString:@"company.zip"]||[car.name isEqualToString:@"com_T8.mp4"])
//                {
                title = [title stringByAppendingFormat:@"、%@", NSLocalizedStringFromTable(car.name, @"InfoPlist", nil)];
//                }
            }
        }
    }
//    "company.zip"   =   "广本品牌";
//    "com_T8.mp4"    =   "本田之手";
//    if([title isEqualToString:@"company.zip"]||[title isEqualToString:@"com_T8.mp4"] )
//    {
    if ([NSString validString:title]) {
        title = [title stringByAppendingFormat:@"资源有最新版本，是否更新？"];
        NSLog(@"%@",title);
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"资源更新提示" message:title delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
        [alertView show];
        [alertView release];
//    }
    
    }
}
- (void)onStartDownload:(NSNotification*)notify {
    CarInfo* carInfo = notify.object;
    [self onStartDownloadTaskAsyncByCarInfo:carInfo];
}

- (void)onCancelDownload:(NSNotification*)notify {
    CarInfo* carInfo =notify.object;
    [[NetworkManager getInstance] cancelTaskByIndentifier:carInfo.name];
}

- (void)decompressionCarZipFile:(CarInfo*) carInfo {
    if (![[NSFileManager defaultManager] fileExistsAtPath:carInfo.downloadCarObj.saveFilePath]) {
        carInfo.downloadCarObj.state = DecompressionError_State;
    } else {
        NSString* car = [[carInfo.name componentsSeparatedByString:@"."] objectAtIndex:0];
        NSString* path = [NSString stringWithFormat:@"%@/%@", carInfo.downloadCarObj.saveAutosPath, car];
        if ([car isEqualToString:@"company"])//|| [car isEqualToString:@"saleTechnique"]
        {
            path = carInfo.downloadCarObj.saveAutosPath;
        }
        BOOL isDir;
        if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir] && isDir) {
            NSError* error = nil;
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            if (nil != error) {
                NSLog(@"error:%@", error);
            }
        }
        
        [[ZipArchiveManager SharedInstance] decompressionWithCarInfo:carInfo];
        carInfo.downloadCarObj.state = Decompressioning_State;
    }
    
    [self.settingView.carsTableView reloadData];
}

- (void)onStartDownloadTaskAsyncByCarInfo:(CarInfo*)carInfo {
    NetworkTask* downloadTask = [[NetworkTask alloc] initWithGetUrl:carInfo.urlStr getArgs:nil];
    NSLog(@"%@",carInfo.urlStr);
    downloadTask.indentifier = carInfo.name;
    downloadTask.isDictionary = NO;
    downloadTask.isNeedProgress = YES;
    [downloadTask setCarInfo:carInfo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUpdateProgress:) name:NetworkTask_NotificationName_OnProgress object:downloadTask];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSuccessDownloadCars:) name:NetworkTask_NotificationName_OnSuccess object:downloadTask];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFailDownloadCars:) name:NetworkTask_NotificationName_OnFail object:downloadTask];
    
    [[NetworkManager getInstance] startTaskAsync:downloadTask level:NetworkManagerTaskLevel_Low];
    NSLog(@"%@",downloadTask);
    SafeRelease(downloadTask);
}

- (void)onUpdateProgress:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    
    for (CarInfo* car in self.carsArr) {
        if ([task.carInfo.downloadCarObj.uuid isEqualToString:car.downloadCarObj.uuid]) {
            
            car.downloadCarObj.progress = task.carInfo.downloadCarObj.progress;
            
            [self.settingView.carsTableView reloadData];
            
            break;
        }
    }
}

- (void)onSuccessDownloadCars:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnProgress object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    for (CarInfo* car in self.carsArr) {
        if ([task.carInfo.downloadCarObj.uuid isEqualToString:car.downloadCarObj.uuid]) {
            car.downloadCarObj.state = Finish_State;
            car.downloadCarObj.progress = task.carInfo.downloadCarObj.progress;
            [self.settingView.carsTableView reloadData];
            
            if (IsVideo != car.downloadCarObj.objType) {
                [self decompressionCarZipFile:car];
            }
            
            break;
        }
    }
}

- (void)onFailDownloadCars:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnProgress object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    for (CarInfo* car in self.carsArr) {
        if ([task.carInfo.downloadCarObj.uuid isEqualToString:car.downloadCarObj.uuid]) {
            car.downloadCarObj.state = DownloadError_State;
            car.downloadCarObj.progress = task.carInfo.downloadCarObj.progress;
            [self.settingView.carsTableView reloadData];
            break;
        }
    }
}


#pragma mark - SettingViewDelegate
- (void)onTapCloseControlSettingView:(SettingView*)settingView {
    [self.view removeFromSuperview];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if ([alertView.title isEqualToString:@"资源更新提示"]){
        if (1 == buttonIndex) {
            for (CarInfo* car in self.carsArr)
            {
                if ((Default_State == car.downloadCarObj.state || DownloadError_State == car.downloadCarObj.state) && [car.downloadCarObj isKindOfClass:[DownloadCarObj class]])
                {
                    car.downloadCarObj.state = Downloading_State;
                    [self onStartDownloadTaskAsyncByCarInfo:car];
                }
            }
        }
    }
}

@end
